package com.lagou;

import com.alibaba.fastjson.JSON;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;

public class InitZkNode {
    private static ZkClient zkClient;

    public static void initNode() throws InterruptedException {
        zkClient = new ZkClient("127.0.0.1:2181");
        System.out.println("会话被创建了..");

        // 判断节点是否存在
        final String path = "/zkServerDruid-Ep";
        boolean exists = zkClient.exists(path);
        DataSourceConfig dataSourceConfig =
                new DataSourceConfig("com.mysql.jdbc.Driver","root","root",
                        "jdbc:mysql://127.0.0.1:3306/zdy_mybatis",5,1,10);

        final String jsonString = JSON.toJSONString(dataSourceConfig);
        System.out.println(jsonString);
        if(!exists){
            // 创建临时节点
            zkClient.createEphemeral(path,jsonString);
        }


        // 读取节点内容
        Object o = zkClient.readData(path);
        System.out.println(o);

        // 注册监听
        zkClient.subscribeDataChanges(path, new IZkDataListener() {

            public void handleDataChange(String s, Object o) throws Exception {
                System.out.println(s+"该节点内容被更新，更新的内容"+o);
                TestDruid.close();
                TestDruid.initDataSource(InitZkNode.getZkClient());
            }

            public void handleDataDeleted(String s) throws Exception {
                System.out.println(s+"该节点被删除,重新建立节点");
                zkClient.createEphemeral(path,jsonString);
            }
        });


        // 更新节点内容
//        zkClient.writeData(path,jsonString);


//        Thread.sleep(Integer.MAX_VALUE);
    }

    public static ZkClient getZkClient() {
        return zkClient;
    }

    public static void setZkClient(ZkClient zkClient) {
        InitZkNode.zkClient = zkClient;
    }

    public static void main(String[] args) throws InterruptedException {
        initNode();


    }

}
